package com.javawebclub.controller;

import java.util.Date;
import java.util.List;

import com.javawebclub.common.model.Article;
import com.javawebclub.common.model.ArticleContent;
import com.jfinal.core.Controller;
/**
 * 
 *Title: ArticleController
 *Description:
 *Tip: 关注公众号：javawebclub
 * @author faymanwang
 * @date 2018年11月4日
 */
public class ArticleController extends Controller {
	/**
	 * 前台详情
	 */
	public void detail(){
		
		Integer articleId=getParaToInt(0);
		Article article=new Article();
		if(articleId!=null&&articleId>0){
			String sql = "select a.*,c.article_content content from article a LEFT JOIN article_content c on a.id = c.article_id where a.id = ?";
			article=Article.dao.findFirst(sql, articleId);
		}
		setAttr("article", article);
		setAttr("content", article.get("content"));
		
		
		render("detail.html");
	}
	/**
	 * 后台列表管理页面
	 */
	public void index(){
		List<Article> articles=Article.dao.find("select a.* from article a where 1=1 and ifnull(a.del_flag,0) !=1");
		setAttr("articles", articles);
		render("list.html");
	}
	/**
	 * 删除
	 */
	public void del(){
		
//		Article.dao.deleteById(getPara(0));
		
		//逻辑删除
		String articleId = getPara(0);
		Article.dao.findById(articleId).set("del_flag", 1).update();
		redirect("/article");
	}
	/**
	 * 编辑
	 */
	public void edit(){
		Integer articleId=getParaToInt(0);
		Article article=new Article();
		if(articleId!=null&&articleId>0){
			String sql = "select a.*,c.article_content content from article a LEFT JOIN article_content c on a.id = c.article_id where a.id = ?";
			article=Article.dao.findFirst(sql, articleId);
		}
		setAttr("article", article);
		setAttr("content", article.get("content"));
		render("form.html");
	}
	
	/**
	 * 表单提交
	 */
	public void submit(){
		//获取基本类型
		Article article=getModel(Article.class, "article");
		//获取内容
		String text = getPara("content");
		
		String sql ="select * from article_content a where a.article_id = ?" ;
		ArticleContent content = ArticleContent.dao.findFirst(sql,article.getId());
		//如果对象不存在则创建内容对象
		if(content==null) {
			content = new ArticleContent();
		}
		content.setArticleContent(text);
		
		if(article!=null){
			if(article.getId()!=null&&article.getId()>0){
				
				article.update();
				content.update();
			}else{
				article.setCreateTime(new Date());				
				article.save();
				content.setArticleId(article.getId());
				content.save();
			}
		}
		redirect("/article");
	}
}
